using System;
using System.Data;
using System.Collections;
using APP.QUANLY.Common;
using RMAS.DAL;

namespace RMAS.DAL
{
    /// <summary>
    /// Summary description for DM_UNIT.
    /// </summary>
    public class DM_UNITDao
    {
        private string _SQLSelectByKey;
        private string _SQLUpdate;
        private string _SQLInsert;
        private string _SQLDelete;
        private string _SQLSelectAll;

        #region Properties

        public IDbConnection _dbConnection;

        public IDbConnection DbConnection
        {
            get { return _dbConnection; }
            set { _dbConnection = value; }
        }

        #endregion

        #region Constructor

        public DM_UNITDao()
        {
            _dbConnection = StaticVar.ServerConnection;
            InitSqlQuery();
        }

        public DM_UNITDao(IDbConnection con)
        {
            _dbConnection = con;
            InitSqlQuery();
        }

        #endregion


        private void ToLowerQuery()
        {
            _SQLDelete = _SQLDelete.ToLower();
            _SQLUpdate = _SQLUpdate.ToLower();
            _SQLInsert = _SQLInsert.ToLower();
            _SQLSelectByKey = _SQLSelectByKey.ToLower();
        }

        private void ToUpperQuery()
        {
            _SQLDelete = _SQLDelete.ToUpper();
            _SQLUpdate = _SQLUpdate.ToUpper();
            _SQLInsert = _SQLInsert.ToUpper();
            _SQLSelectByKey = _SQLSelectByKey.ToUpper();
        }

        #region InitSqlQuery
        private void InitSqlQuery()
        {
            string query;

            query = @"SELECT ID, Name, Note, IDPOS FROM DM_UNIT WHERE (ID = @ID)";
            _SQLSelectByKey = query;

            query = @"UPDATE DM_UNIT SET Name = @Name, Note = @Note, IDPOS = @IDPOS WHERE (ID = @ID)";
            _SQLUpdate = query;

            query = @"INSERT INTO DM_UNIT VALUES (@ID, @Name, @Note, @IDPOS)";
            _SQLInsert = query;

            query = @"DELETE FROM DM_UNIT WHERE (ID = @ID)";
            _SQLDelete = query;

            query = @"SELECT ID, Name, Note, IDPOS FROM DM_UNIT";
            _SQLSelectAll = query;
        }
        #endregion
        public void LoadByCommandText(string commandtext, IDbTransaction trans)
        {
            if (_dbConnection == null)
            {
                throw new Exception("Connection has not been set.");
            }

            IDbCommand command;

            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }

                command = _dbConnection.CreateCommand();
                command.CommandText = commandtext;

                if (trans != null) { command.Transaction = trans; }
                if (command.ExecuteNonQuery() == 0) { throw new Exception("Zero rows were affected."); }
            }
            catch (Exception ex) { throw ex; }
        }

        #region Save & Delete
        private void Save(DM_UNIT obj, IDbTransaction trans, bool isExisting)
        {
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }

            IDbCommand command;

            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
                command = _dbConnection.CreateCommand();

                if (!isExisting) { command.CommandText = _SQLInsert + ";"; }
                else { command.CommandText = _SQLUpdate + ";"; }

                DalTools.addDbDataParameter(command, "ID", obj.ID, DbType.String);
                DalTools.addDbDataParameter(command, "Name", obj.Name, DbType.String);
                DalTools.addDbDataParameter(command, "Note", obj.Note, DbType.String);
                DalTools.addDbDataParameter(command, "IDPOS", obj.IDPOS, DbType.String);

                if (trans != null) { command.Transaction = trans; }
                if (command.ExecuteNonQuery() == 0) { throw new Exception("Zero rows were affected."); }
            }
            catch (Exception ex) { throw ex; }
        }

        public void Delete(DM_UNIT obj, IDbTransaction trans)
        {
            if (_dbConnection == null)
            {
                //throw new DalException("Connection has not been set.");
                throw new Exception("Connection has not been set.");
            }

            IDbCommand command;

            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }

                command = _dbConnection.CreateCommand();
                command.CommandText = _SQLDelete + ";";

                DalTools.addDbDataParameter(command, "ID", obj.ID, DbType.String);

                if (trans != null) { command.Transaction = trans; }
                if (command.ExecuteNonQuery() == 0) { throw new Exception("Zero rows were affected."); }
            }
            catch (Exception ex) { throw ex; }
        }

        public void Insert(DM_UNIT obj, IDbTransaction trans)
        {
            Save(obj, trans, false);
        }
        public void Update(DM_UNIT obj, IDbTransaction trans)
        {
            Save(obj, trans, true);
        }
        #endregion

        #region Command Execute & Read Properties

        private DM_UNITList SelectListByCommand(IDbCommand command)
        {
            DM_UNITList list = new DM_UNITList();
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }
            try
            {
                DM_UNIT obj;
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
                using (IDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        obj = new DM_UNIT();
                        ReadProperties(obj, reader);
                        list.Add(obj);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return list;
        }

        private DM_UNITList SelectListByCommand(IDbCommand command, IDbTransaction trans)
        {
            DM_UNITList list = new DM_UNITList();
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }
            try
            {
                DM_UNIT obj;
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
                command.Transaction = trans;
                using (IDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        obj = new DM_UNIT();
                        ReadProperties(obj, reader);
                        list.Add(obj);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return list;
        }

        private void DeleteListByCommand(IDbCommand command, IDbTransaction trans)
        {
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }
            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
                if (trans != null) { command.Transaction = trans; }
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void ReadProperties(DM_UNIT obj, IDataReader reader)
        {
            try
            {
                if (!(reader["ID"] is DBNull))
                {
                    obj.ID = (string)reader["ID"];
                }
                if (!(reader["Name"] is DBNull))
                {
                    obj.Name = (string)reader["Name"];
                }
                if (!(reader["Note"] is DBNull))
                {
                    obj.Note = (string)reader["Note"];
                }
                if (!(reader["IDPOS"] is DBNull))
                {
                    obj.IDPOS = (string)reader["IDPOS"];
                }
            }
            catch (Exception ex)
            {
                throw new DalException("Failed to read properties from DataReader.", ex);
            }
        }
        #endregion

        public DM_UNIT SelectByKey(string ID)
        {
            IDbCommand command = _dbConnection.CreateCommand();
            command.CommandText = _SQLSelectByKey;
            DalTools.addDbDataParameter(command, "ID", ID, DbType.String);
            DM_UNITList list = SelectListByCommand(command);

            if (list.Count == 0) { throw new Exception("No data was returned"); }
            return list[0];
        }

        public DM_UNIT SelectByKey(string ID, IDbTransaction trans)
        {
            IDbCommand command = _dbConnection.CreateCommand();
            command.CommandText = _SQLSelectByKey;
            DalTools.addDbDataParameter(command, "ID", ID, DbType.String);
            DM_UNITList list = SelectListByCommand(command, trans);

            if (list.Count == 0) { throw new Exception("No data was returned"); }
            return list[0];
        }

        public DM_UNITList SelectAll()
        {
            IDbCommand command = _dbConnection.CreateCommand();
            if (!StaticVar.IsServer)
            {
                _SQLSelectAll = _SQLSelectAll + " WHERE IDPOS = @IDPOS";
                DalTools.addDbDataParameter(command, "IDPOS", StaticVar.CPUID, DbType.String);
            }
            command.CommandText = _SQLSelectAll;
            DM_UNITList list = SelectListByCommand(command);
            return list;
        }
        public DM_UNITList SelectAll(IDbTransaction trans)
        {
            IDbCommand command = _dbConnection.CreateCommand();
            if (!StaticVar.IsServer)
            {
                _SQLSelectAll = _SQLSelectAll + " WHERE IDPOS = @IDPOS";
                DalTools.addDbDataParameter(command, "IDPOS", StaticVar.CPUID, DbType.String);
            }
            command.CommandText = _SQLSelectAll;
            DM_UNITList list = SelectListByCommand(command, trans);
            return list;
        }
        public DM_UNITList SelectByCommand(string Command)
        {
            IDbCommand command = _dbConnection.CreateCommand();
            command.CommandText = Command;
            DM_UNITList list = SelectListByCommand(command);
            return list;
        }

        public DM_UNITList SelectByCondition(DM_UNIT obj, IDbTransaction trans)
        {
            IDbCommand command = _dbConnection.CreateCommand();
            command.CommandText = "SELECT * FROM DM_UNIT " + GetCondtionQuery(obj) + ";";
            FillParamToCommand(command, obj);
            DM_UNITList list = SelectListByCommand(command, trans);
            return list;
        }

        public DM_UNITList SelectByCondition(DM_UNIT obj)
        {
            IDbCommand command = _dbConnection.CreateCommand();
            command.CommandText = "SELECT * FROM DM_UNIT " + GetCondtionQuery(obj) + ";";
            FillParamToCommand(command, obj);
            DM_UNITList list = SelectListByCommand(command);
            return list;
        }
        private void DeleteByCondition(DM_UNIT obj, IDbTransaction trans)
        {
            IDbCommand command = _dbConnection.CreateCommand();
            command.CommandText = "DELETE FROM DM_UNIT " + GetCondtionQuery(obj) + ";";
            FillParamToCommand(command, obj);
            DeleteListByCommand(command, trans);
        }

        #region Make Condition Query & Fill Param from Condition to Command
        private string GetCondtionQuery(DM_UNIT obj)
        {
            if (obj == null) { return ""; }
            string s = "";
            if (obj.IsSetID)
            {
                s += " AND ID = @ID ";
            }
            if (obj.IsSetName)
            {
                s += " AND Name = @Name ";
            }
            if (obj.IsSetNote)
            {
                s += " AND Note = @Note ";
            }
            if (obj.IsSetIDPOS)
            {
                s += " AND IDPOS = @IDPOS ";
            }
            if (s.Length > 0)
            {
                s = " WHERE " + s.Substring(4);
                return s;
            }
            return "";
        }

        private void FillParamToCommand(IDbCommand command, DM_UNIT obj)
        {
            if (obj == null) { return; }
            if (obj.IsSetID)
            {
                DalTools.addDbDataParameter(command, "ID", obj.ID, DbType.String);
            }
            if (obj.IsSetName)
            {
                DalTools.addDbDataParameter(command, "Name", obj.Name, DbType.String);
            }
            if (obj.IsSetNote)
            {
                DalTools.addDbDataParameter(command, "Note", obj.Note, DbType.String);
            }
            if (obj.IsSetIDPOS)
            {
                DalTools.addDbDataParameter(command, "IDPOS", obj.IDPOS, DbType.String);
            }
        }
        #endregion
    }
}